package cn.hh.wechatkit.api.card;

import cn.hh.wechatkit.data.postdata.card.Meta_ICard;
import cn.hh.wechatkit.data.returndata.card.Meta_RData_CreateCard;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hhchat.kit.http.httpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static cn.hh.wechatkit.helper.WxConst.CreateCard_Post_URL;


/**
 * Created this one by HMH on 2017/5/6.
 */
public class WxAPI_Card_Create_Api {

    private final static Logger logger = LoggerFactory.getLogger(WxAPI_Card_Create_Api.class);

    /**
     * 创建卡券
     * @param card 卡券实体
     * @param ACCESS_TOKEN 基础令牌
     * @return 创建结果
     * @throws IOException io异常
     * @throws Wx_Exception_InvalidResponse 响应异常
     */
    public static Meta_RData_CreateCard createWxCard(Meta_ICard card, String ACCESS_TOKEN) throws IOException, Wx_Exception_InvalidResponse {
        //获取参数,替换参数
        String url = CreateCard_Post_URL.replace("ACCESS_TOKEN", ACCESS_TOKEN);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("card", card);
        String jsonCard = jsonObject.toJSONString();
        //生成Request
        Response response = httpUtil.postJson(url, jsonCard);
        //获取数据
        if (response != null) {
            String body = response.body().string();
            return JSON.parseObject(body, Meta_RData_CreateCard.class);
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");
    }
}
